package com.okaysoft.ofb

import grails.converters.JSON

class FormworkService {

    def save(Map map) {
        def formworkInstance
        def compositionA = map.composition_a//A面布局
        def compositionB = map.composition_b //B面布局
        def aNum = 0  //A面布局区块数
        def bNum = 0  //B面布局区块数
        if (compositionA) {
            def cas = compositionA.tokenize("_")
            aNum = cas[1] as int
        }
        if (compositionB) {
            def cbs = compositionB.tokenize("_")
            bNum = cbs[1] as int
        }

        if (map.id) {
            formworkInstance = Formwork.get(map.id)
        }
        if (!formworkInstance) {
            formworkInstance = new Formwork()
        }

        formworkInstance.properties = map

        def formworkCategory = FormworkCategory.get(map.formworkCategoryId)
        if (formworkCategory){
            formworkInstance.formworkCategory = formworkCategory
        }

        //保存模板
        if (!formworkInstance.save(flush: true)) {
            throw new RuntimeException("模板参数不正确，保存失败")
        }

        def fdw = FormworkDetail.where {
            formwork==formworkInstance && category== FormworkDetail.Category.A
        }
        def formworkDetail = fdw.find()
        if (!formworkDetail) {
            formworkDetail = new FormworkDetail()
            formworkDetail.formwork = formworkInstance
            formworkDetail.category = FormworkDetail.Category.A
        }
        formworkDetail.composition = compositionA

        //a面布局保存
        if(!formworkDetail.save(flush: true)  ){
            throw new RuntimeException("模板A面参数不正确，保存失败")
        }

        //删除布局区块参数
        FormworkComposition.executeUpdate("delete FormworkComposition c where c.formworkDetail = :formworkDetail",
                [formworkDetail: formworkDetail])

        //重新插入区块参数
        for (def i=1;i<=aNum;i++){
            def formworkComposition =  new FormworkComposition()
            formworkComposition.formworkDetail = formworkDetail
            formworkComposition.number = i
            def area = map."a$i"
            def areas = area.tokenize('|')
            formworkComposition.category =  FormworkComposition.Category."${areas[0]}"
            formworkComposition.quantity = areas[1] as int
            if(!formworkComposition.save(flush: true) ){
                throw new RuntimeException("模板A面布局参数不正确，保存失败")
            }
        }

        def fdwb = FormworkDetail.where {
            formwork==formworkInstance && category== FormworkDetail.Category.B
        }
        def formworkDetailB = fdwb.find()
        if (!formworkDetailB) {
            formworkDetailB = new FormworkDetail()
            formworkDetailB.formwork = formworkInstance
            formworkDetailB.category = FormworkDetail.Category.B
        }
        formworkDetailB.composition = compositionB

        //b面布局保存
        if(!formworkDetailB.save(flush: true)  ){
            throw new RuntimeException("模板B面参数不正确，保存失败")
        }

        //删除布局区块参数
        FormworkComposition.executeUpdate("delete FormworkComposition c where c.formworkDetail = :formworkDetailB",
                [formworkDetailB: formworkDetailB])

        //重新保存b面布局区块参数
        for (def i=1;i<=bNum;i++){
            def formworkComposition =  new FormworkComposition()
            formworkComposition.formworkDetail = formworkDetailB
            formworkComposition.number = i
            def area = map."b$i"
            def areas = area.tokenize('|')
            formworkComposition.category =  FormworkComposition.Category."${areas[0]}"
            formworkComposition.quantity = areas[1] as int
            formworkComposition.save(flush: true)
            if(!formworkComposition.save(flush: true) ){
                throw new RuntimeException("模板B面布局参数不正确，保存失败")
            }
        }

    }
    
    def listJson(Map params = Collections.emptyMap()) {
        def total =  0
        def formworks
        
        if (!params || !params.categoryId) {
            return ([rows:[],total:0] as JSON)
        }
        def categoryId = params.categoryId
        if (params.category_name && categoryId){
            def query = Formwork.where {
                formworkCategory.id == categoryId as Long && (name ==~ "%${params.category_name}%")
            }
            total = query.count()
            formworks = query.list(params)
        }else{
            total =  categoryId?Formwork.countByFormworkCategory(FormworkCategory.get(categoryId)):0
            formworks = categoryId?Formwork.findAllByFormworkCategory(FormworkCategory.get(categoryId),params):[]
        }
        formworks = formworks.collect {fw->
            formworkCompositionData(fw)
        }
        return ([rows:formworks,total:total] as JSON)
    }

    def formworkCompositionData(Formwork formwork) {
        def compositionA
        def compositionB
        def areaa = [:]
        def fwds = formwork.formworkDetails
        fwds.each {fwd->
            if(fwd.category == FormworkDetail.Category.A) {
                compositionA = fwd.composition
                def ac = fwd.formworkCompositions
                ac.eachWithIndex {a,i->
                    def index = a.number//i+1
                    areaa << ["a${index}":[category:a.category.name(),quantity:a.quantity]]
                }
            }
            if(fwd.category == FormworkDetail.Category.B) {
                compositionB = fwd.composition
                def ac = fwd.formworkCompositions
                ac.eachWithIndex {b,i->
                    def index = b.number
                    areaa << ["b${index}":[category:b.category.name(),quantity:b.quantity]]
                }
            }
        }
        [id:formwork.id,name:formwork.name,description:formwork.description,composition_a:compositionA,composition_b:compositionB]<< areaa
    }

    def formworkCategoryTreeJson(parentId) {
        def formworkCategorys
        if(!parentId) {
            formworkCategorys = FormworkCategory.findAllByParentIdIsNull()
        }else{
            formworkCategorys = FormworkCategory.findAllByParentId(parentId)
        }

        if(!formworkCategorys || formworkCategorys.size() == 0) {
            return []
        }
        return formworkCategorys.collect {formworkCategory->
            [id: formworkCategory.id,text: formworkCategory.name,children: formworkCategoryTreeJson(formworkCategory.id)]
        }
    }

    def formworkTreeJson(parentId) {
        def formworkCategorys
        if(!parentId) {
            formworkCategorys = FormworkCategory.findAllByParentIdIsNull()
        }else{
            formworkCategorys = FormworkCategory.findAllByParentId(parentId)
        }

        if(!formworkCategorys || formworkCategorys.size() == 0) {
            return []
        }
        return formworkCategorys.collect {formworkCategory->
            def formworks = Formwork.findAllByFormworkCategory(formworkCategory)
            if(formworks) {
                formworks = formworks.collect {formwork->
                    [id:formwork.id,text: formwork.name]
                }
                formworks = formworks + formworkTreeJson(formworkCategory.id)
            }else{
                formworks = formworkTreeJson(formworkCategory.id)
            }
            [id: "fc-${formworkCategory.id}",text: formworkCategory.name,children: formworks]
        }
    }
}
